<template>
    <rui-page :defines="defines">
        <Row>
            <rui-query :label-width="120"
                       :query="queryParamData"
                       :query-rows="queryRows"
                       ref="paramQuery"
            />
        </Row>
        <rui-table :defineId="'flowParamConfig'"
                   :fixedLeft="['greatWallServiceId','flowName']"
                   :fixedRight="['action']"
                   :showIndex="false"
                   :select="false"
                   :slots="[{key:'action',slot:'action'}]"
                   @loadDatas="queryParamData"
                   ref="paramTable"
                   ref-query="paramQuery">
            <template slot="toolBar">
                <Button @click="createParam" icon="ios-add" type="primary" >添加</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary" >编辑</Button>
                    <Button @click="delParam(row)" size="small" type="error">删除</Button>
                    <Button v-show="row.paramType!='input'" @click="paramComponentConfig(row)" size="small" type="warning">参数配置</Button>
                </div>
            </template>
        </rui-table>
        <Modal
            :closable="false"
            :mask-closable="false"
            :title="paramConfigTitle"
            :width="1000"
            v-model="paramConfig">
            <rui-form :afterChange="editFromChange"
                      :form-options="paramConfigFormOptions"
                      :label-width="120"
                      :read-only="false"
                      ref="editForm">
                <template  slot="paramTypeSlot" slot-scope="{ key,item,data }">
                    <Select v-model="data[key]" style="width:200px">
                        <Option v-for="type in paramTypes" :value="type.value" :key="type.value">{{ type.title }}</Option>
                    </Select>
                </template>
            </rui-form>
            <div slot="footer">
                <Button @click="paramConfig = false" size="small">取消</Button>
                <Button @click="checkParamConfig" size="small" type="primary">保存</Button>
            </div>
        </Modal>
        <Modal
            :closable="false"
            :mask-closable="false"
            :title="componentConfigTitle"
            v-model="componentConfig">
            <Form :label-width="100" :model="paramComponentInfo.paramConfigInfo" :rules="validateRules"
                  ref="componentConfigForm">
                <FormItem label="字典编号" prop="dicKey" v-if="paramComponentInfo.componentInfo.paramType==='dic'">
                    <Input placeholder="输入字典编号" type="text" v-model="paramComponentInfo.paramConfigInfo.dicKey">
                    </Input>
                </FormItem>

                <FormItem label="请求方法" prop="method" v-if="paramComponentInfo.componentInfo.paramType !=='dic'">
                    <Select v-model="paramComponentInfo.paramConfigInfo.method">
                        <Option value="get">GET</Option>
                        <Option value="post">POST</Option>
                    </Select>
                </FormItem>

                <FormItem label="请求服务" prop="serviceName" v-if="paramComponentInfo.componentInfo.paramType !=='dic'">
                    <Input placeholder="输入请求服务" type="text" v-model="paramComponentInfo.paramConfigInfo.serviceName">
                    </Input>
                </FormItem>

                <FormItem label="请求路径" prop="uri" v-if="paramComponentInfo.componentInfo.paramType !=='dic'">
                    <Input placeholder="输入请求路径" type="text" v-model="paramComponentInfo.paramConfigInfo.uri">
                    </Input>
                </FormItem>

                <FormItem label="请求参数" prop="params" v-if="paramComponentInfo.componentInfo.paramType !=='dic'">
                    <Input placeholder="输入请求参数" type="textarea" v-model="paramComponentInfo.paramConfigInfo.params">
                    </Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="componentConfig = false" size="small">取消</Button>
                <Button @click="checkParamComponentConfig" size="small" type="primary">保存</Button>
            </div>
        </Modal>
    </rui-page>
</template>

<script>
    import flowParamDefine from "./defines/flow-param-define";
    import {listFlowParam, saveFlowParam, deleteFlowParam} from "_p/basic/api/flowconfig/flow-param-config"
    import {deepClone} from "@/libs/utils/ObjectClone";
    import defaultParamComponentInfo from './constant/flow-component'

    export default {
        name: "flow-param-config",
        data() {
            return {
                defines:[],
                paramConfig: false,
                componentConfig: false,
                modelType: '',
                paramConfigTitle: '流程参数编辑',
                componentConfigTitle: '参数取值配置',
                validateRules: {},
                paramTypes:[],
                paramComponentInfo: {
                    paramConfigInfo: {},
                    componentInfo: {}
                },
                queryRows: [
                    {
                        defineId: 'flowParamConfig',
                        totalSpan: 16,
                        fields: ['flowName', 'paramName']
                    }
                ],
                paramConfigFormOptions: [
                    {
                        isGroup: false,
                        grids: [
                            {defineId: 'flowParamConfig', span: 8, fields: ['greatWallServiceId','gwFlowParamType']},
                            {defineId: 'flowParamConfig', span: 8, fields: ['paramKey', 'paramType'],slots: [{key: 'paramType', slotName: 'paramTypeSlot'}]},
                            {defineId: 'flowParamConfig', span: 8, fields: ['paramName', 'paramValueExpress']}
                        ]
                    }
                ]
            };
        },
        methods: {
            queryParamData(queryData) {
                listFlowParam(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.paramTable.updateTableData(records, total);
                    }
                });
            },
            createParam() {
                this.paramConfigTitle = '新建流程参数';
                this.$refs.editForm.setAllFieldRequired(true);
                this.modelType = 'new';
                let self = this;
                this.$nextTick(() => {
                    self.$refs.editForm.resetFrom();
                    this.paramConfig = true;
                })
            },
            delParam(row) {
                let self = this;
                this.$Modal.confirm({
                    title: "确认",
                    content: `确认删除该参数[${row.paramName}]？`,
                    onOk: () => {
                        deleteFlowParam(row).then(res => {
                            self.$refs['paramTable'].reloadData();
                        })
                    }
                });
            },
            paramComponentConfig(row) {
                this.componentConfigTitle = '配置' + row.paramName + "(" + row.paramKey + ") 取值";
                this.paramComponentInfo.componentInfo = row;
                this.validateRules = defaultParamComponentInfo.getValidateRules(row.paramType=='dic'?'dic':'requestParam');
                this.paramComponentInfo.paramConfigInfo = defaultParamComponentInfo.genComponentConfig(row.paramType=='dic'?'dic':'requestParam', JSON.parse(row.paramConfig));
                this.$refs['componentConfigForm'].resetFields();
                this.componentConfig = true;
            },
            edit(row) {
                this.paramConfigTitle = '配置' + row.paramName + "(" + row.paramKey + ")";
                this.modelType = 'modify';
                this.$refs.editForm.updateFormData(deepClone(row));
                this.$refs.editForm.setAllFieldRequired(true);
                this.paramConfig = true;
            },
            checkParamConfig() {
                let self = this;
                this.$refs.editForm.getForm().validate((valid) => {
                    if (valid) {
                        let reqData = self.$refs.editForm.getFormData();
                        if (self.modelType === 'new') {
                            reqData.paramConfig = '{}';
                            saveFlowParam(reqData).then(res => {
                                if (res.code === '0000') {
                                    self.$refs['paramTable'].reloadData();
                                    self.paramConfig = false;
                                } else {
                                    self.$Message.error(res.msg);
                                }
                            }).catch(err => {
                                self.$Message.error("参数保存失败");
                            })
                        } else if (self.modelType === 'modify') {
                            saveFlowParam(reqData).then(res => {
                                if (res.code === '0000') {
                                    self.$refs['paramTable'].reloadData();
                                    self.paramConfig = false;
                                } else {
                                    self.$Message.error(res.msg);
                                }
                            }).catch(err => {
                                self.$Message.error("参数保存失败");
                            })
                        }
                    } else {
                        self.paramConfig = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            checkParamComponentConfig() {
                let self = this;
                this.$refs.componentConfigForm.validate((valid) => {
                    if (valid) {
                        self.paramComponentInfo.componentInfo.paramConfig = JSON.stringify(self.paramComponentInfo.paramConfigInfo);
                        saveFlowParam(self.paramComponentInfo.componentInfo).then(res => {
                            if (res.code === '0000') {
                                self.$refs['paramTable'].reloadData();
                                self.componentConfig = false;
                                self.$refs.componentConfigForm.resetFields();
                            } else {
                                self.$Message.error(res.msg);
                            }
                        })
                    } else {
                        self.componentConfig = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            editFromChange(key, afterValue) {
                if (key === 'gwFlowParamType') {
                    if (afterValue === 'select') {
                        this.paramTypes.splice(0, this.paramTypes.length);
                        this.paramTypes.push(...defaultParamComponentInfo.selectParamTypes)
                    } else {
                        this.paramTypes.splice(0, this.paramTypes.length);
                        this.paramTypes.push(...defaultParamComponentInfo.allParamTypes)
                    }
                }
            }
        },
        computed: {
        },
        created(){
            this.defines.push({
                id: 'flowParamConfig',
                fields: flowParamDefine
            })
        },
        mounted() {
            this.$refs['paramTable'].reloadData();
        }
    };
</script>
